<template>
    <div class="check-rule-table">
        <el-row class="search-box">
            <el-button v-authCode="B_0094" type="primary" size="mini" @click="queryDialog = true">查询</el-button>
            <el-button v-authCode="B_0094" type="primary" size="mini" @click="openDialog(1, '')">新增</el-button>
            <el-button v-authCode="B_0094" type="primary" size="mini" @click="openStatusDialog('1')">启用</el-button>
            <el-button v-authCode="B_0094" type="danger" size="mini" @click="openStatusDialog('0')">禁用</el-button>
            <el-button v-authCode="B_0094" type="primary" size="mini" @click="handleExport('sql')">导出sql脚本</el-button>
            <el-button v-authCode="B_0094" type="primary" size="mini" @click="handleExport('facOrBound')">全部导出JSON</el-button>
        </el-row>
        <el-row class="table-content">
            <el-table
                :data="ruleData"
                v-table-top="rulePage.currentPage"
                @selection-change="handleSelectionChange"
                border
                size="mini"
                style="width: 100%"
                height="calc(100vh - 210px)"
                @sort-change="handleSort"
            >
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column prop="ruleId" label="规则序号" width="100" show-overflow-tooltip> </el-table-column>
                <el-table-column label="指标编号" width="120" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>{{ scope.row.boundCode || scope.row.enCalFacCode || '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="指标类型" width="120" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <!-- <span>{{ scope.row.boundCode ? '范围' : '因子' }}</span> -->
                        <span v-if="scope.row.boundCode">范围</span>
                        <span v-else-if="scope.row.enCalFacCode">因子</span>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column label="指标名称" show-overflow-tooltip width="180">
                    <template slot-scope="scope">
                        <span>{{ scope.row.boundName || scope.row.enCalFacName || '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="ruleSource" label="规则来源" width="120" show-overflow-tooltip> </el-table-column>
                <el-table-column
                    prop="ruleType"
                    label="规则类型"
                    width="120"
                    :formatter="(row, column) => ruleType[row.ruleType]"
                    show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column prop="ruleGrade" label="勾稽等级" width="120" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.ruleGrade === '1'" style="color: orange">警告</span>
                        <span v-if="scope.row.ruleGrade === '2'" style="color: red">错误</span>
                    </template>
                </el-table-column>
                <el-table-column prop="isOpen" label="状态" width="120" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.isOpen === '1'" type="success" size="mini">已开启</el-tag>
                        <el-tag v-if="scope.row.isOpen === '0'" type="danger" size="mini">已禁用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="ruleName" label="规则名称" show-overflow-tooltip width="180"></el-table-column>
                <el-table-column prop="ruleDescroption" label="规则说明" width="180" show-overflow-tooltip> </el-table-column>

                <el-table-column prop="createDate" label="创建日期" show-overflow-tooltip align="center" width="180" sortable="custon">
                    <template slot-scope="scope">
                        <span>{{ dateFormat(scope.row.createDate) }} {{ timeFormat(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="createTime" label="创建时间" width="120" show-overflow-tooltip align="center"> </el-table-column> -->
                <el-table-column label="操作" width="150" fixed="right">
                    <template slot-scope="scope">
                        <RiskIconButton
                            type="primary"
                            icon="el-icon-view"
                            topTitle="查看详情"
                            @on-click="openDialog(3, scope.row.ruleId)"
                        ></RiskIconButton>
                        <RiskIconButton
                            type="primary"
                            icon="el-icon-edit"
                            topTitle="编辑详情"
                            @on-click="openDialog(2, scope.row.ruleId)"
                        ></RiskIconButton>
                        <RiskIconButton type="danger" icon="el-icon-delete" topTitle="删除" @on-click="handleRemove(scope.row)"></RiskIconButton>
                    </template>
                </el-table-column>
            </el-table>
            <div class="block">
                <risk-pagination :paging="rulePage" @page-change="queryRuleList"></risk-pagination>
            </div>
        </el-row>
        <!-- 查询 -->
        <yh-dialog
            drag
            title="查询条目信息"
            :visible.sync="queryDialog"
            width="430px"
            v-loading="loading"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form label-width="150" size="mini" ref="queryForm" :model="queryForm">
                <el-form-item label="规则序号" prop="ruleId">
                    <el-input style="width: 220px" v-model="queryForm.ruleId"></el-input>
                </el-form-item>
                <el-form-item label="规则名称" prop="ruleName">
                    <el-input style="width: 220px" v-model="queryForm.ruleName"></el-input>
                </el-form-item>
                <el-form-item label="指标编号" prop="boundCode">
                    <el-input style="width: 220px" v-model="queryForm.boundCode"></el-input>
                </el-form-item>

                <el-form-item label="指标类型" prop="boundType">
                    <el-select style="width: 220px" v-model="queryForm.boundType" placeholder="请选择">
                        <el-option v-for="(value, key) in boundTypeSelectData" :key="key" :label="key + ' ' + value" :value="key"> </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="规则来源" prop="ruleSource">
                    <el-select style="width: 220px" v-model="queryForm.ruleSource" placeholder="请选择">
                        <el-option v-for="(value, key) in ruleSourceSelectData" :key="key" :label="value" :value="key"> </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="勾稽等级" prop="ruleGrade">
                    <el-select style="width: 220px" v-model="queryForm.ruleGrade" placeholder="请选择">
                        <el-option v-for="(value, key) in gradeSelectData" :key="key" :label="key + ' ' + value" :value="key"> </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="closeQueryDialog"> 取 消 </el-button>
                <el-button size="mini" @click="resetForm"> 重 置 </el-button>
                <el-button size="mini" type="primary" @click="submitQueryForm"> 确 定 </el-button>
            </div>
        </yh-dialog>

        <!-- 删除 -->
        <div>
            <yh-dialog drag title="确定要删除勾稽规则吗？" :visible.sync="delDialog" width="500px">
                <div class="remove-text">
                    <span> {{ ruleId + '--' + ruleName }}</span>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="delDialog = false">取 消</el-button>
                    <el-button size="mini" type="primary" @click="delRule">确 定</el-button>
                </div>
            </yh-dialog>
        </div>

        <!-- 启用、禁用 -->
        <div>
            <yh-dialog drag title="确定要启用/停用勾稽规则吗？" :visible.sync="statusDialog" width="500px">
                <div class="remove-text">
                    <span> {{ selectDynamicCodes.join(' , ') }}</span>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="statusDialog = false">取 消</el-button>
                    <el-button size="mini" type="primary" @click="handleChangeStatus">确 定</el-button>
                </div>
            </yh-dialog>
        </div>

        <!-- 新增、编辑、查看 -->
        <CheckSettingDetail :dialogVO="dialogVO" v-if="dialogVO.visible" :ruleId="ruleId" @refresh="refresh" />
    </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import RiskTable from '@/common/components/risk-table.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import Invest from '@/common/dict/invest';
import Index from '@/pages/setting/dict';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { downLoadFile } from '@/utils/request';
import { DialogVO } from '@yhfin/biz';
import CheckSettingDetail from './check-setting-detail.vue';
import { timeFormat, dateFormat } from '@/utils/tools';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'CheckRuleTable',
    components: {
        RiskTable,
        RiskIconButton,
        CheckSettingDetail,
        RiskPagination,
    },
})
export default class CheckRuleTable extends Vue {
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    private ruleData: any[] = [];

    private Invest: any = new Invest();
    private dict: any = new Index();
    private queryDialog: boolean = false;
    private delDialog: boolean = false;

    // 新增、编辑、查看弹框对象
    private dialogVO: DialogVO = new DialogVO();

    private rulePage: pages = {
        total: 0,
        pageSize: 25,
        currentPage: 1,
    };

    private queryForm = {
        ruleId: '',
        ruleName: '',
        ruleGrade: '',
        boundCode: '',
        // 指标类型
        boundType: '',
        // 规则来源
        ruleSource: '',
    };

    // 指标类型下拉数据
    private boundTypeSelectData = {
        '1': '因子',
        '2': '范围',
    };

    // 规则来源下拉数据
    private ruleSourceSelectData = {
        静态: '静态',
        实时: '实时',
    };
    // 勾稽等级下拉数据
    private gradeSelectData = {
        '1': '警告',
        '2': '错误',
    };

    private ruleType = {
        '1': '表数据量配置',
        '2': '关联关系一对一配置',
        '3': '关联关系一对多配置',
        '4': '字段字典配置',
        '5': '字段日期配置',
        '6': '字段时间配置',
        '7': '字段非NULL配置',
        '8': '自定义sql配置',
        '9': '存储过程',
    };
    selectDynamicCodes: any[] = [];
    formData: any = {};
    ruleId: string = '';
    ruleName: string = '';
    statusDialog: boolean = false;
    status: string = '';
    sort: string = '';
    // 排序字段
    sortableObj = {
        createDate: 'CONCAT(D_CREATE_DATE,D_CREATE_TIME)',
    };

    async mounted() {
        this.queryRuleList(this.rulePage.currentPage);
    }

    refresh() {
        this.queryRuleList(this.rulePage.currentPage);
    }

    // 转表格筛选下拉框数据
    objToArr(param) {
        let list = [];
        for (let key in param) {
            list.push({ value: key, label: param[key] });
        }
        return list;
    }

    //  获取勾稽规则列表
    private queryRuleList(val?: number): void {
        if (val) {
            this.rulePage.currentPage = val;
        }
        this.$axios
            .post('/checkRule/list', {
                ...this.queryForm,
                paging: {
                    currentPage: this.rulePage.currentPage,
                    pageSize: this.rulePage.pageSize,
                },
                sort: this.sort
            })
            .then((res: any) => {
                this.ruleData = res.list;

                this.rulePage.total = res.total;
            })
            .catch(e => {
                console.log(e);
            });
    }

    private closeQueryDialog() {
        this.queryDialog = false;
    }

    // 重置查询表单
    private resetForm() {
        (this.$refs.queryForm as any).resetFields();
    }

    private submitQueryForm() {
        this.$axios
            .post('/checkRule/list', {
                ...this.queryForm,
                paging: {
                    currentPage: 1,
                    pageSize: 25,
                },
            })
            .then((res: any) => {
                this.ruleData = res.list;
                this.rulePage.total = res.total;
                this.queryDialog = false;
                this.yh_message_success('查询成功');
            })
            .catch(e => {
                console.log(e);
            });
    }

    // 获取表格勾选数据
    private handleSelectionChange(val: any) {
        this.selectDynamicCodes = [];
        for (var i in val) {
            this.selectDynamicCodes.push(val[i].ruleId);
        }
    }

    /**
     * 导出sql脚本/JSON
     */
    handleExport(type) {
        let selectKey = this.selectDynamicCodes;
        downLoadFile({
            url: '/checkRule/export',
            method: 'post',
            data: {
                ...this.queryForm,
                exportBySql: type === 'sql',
                selectKey: selectKey,
            },
            loading: true,
            loadingMsg: '正在准备导出，请稍后··· ···',
        });
    }

    // 勾稽规则处理
    private openDialog(type, ruleId) {
        this.ruleId = ruleId;
        if (type === 1) {
            this.dialogVO = this.dialogVO.getAddDialog('新增勾稽规则');
        } else if (type === 2) {
            this.dialogVO = this.dialogVO.getUpdateDialog('编辑勾稽规则');
        } else if (type === 3) {
            this.dialogVO = this.dialogVO.getSeeDialog('查看勾稽规则');
        }
    }

    private openStatusDialog(status: string) {
        if (this.selectDynamicCodes.length === 0) {
            this.yh_message_warn('请选择规则');
            return;
        }
        this.statusDialog = true;
        this.status = status;
    }

    // 启用、禁用规则
    private handleChangeStatus() {
        this.$axios.post('/checkRule/enOrUnAble/' + this.status, this.selectDynamicCodes).then((res: any) => {
            this.statusDialog = false;
            this.refresh();
            this.yh_message_success('启用/停用成功');
        });
    }

    handleRemove(row: any) {
        this.ruleId = row.ruleId;
        this.ruleName = row.ruleName;
        this.delDialog = true;
    }

    // 删除勾稽规则
    private delRule() {
        this.$axios({
            url: '/checkRule/del/' + this.ruleId,
            method: 'get',
        }).then(res => {
            this.yh_message_success('删除成功');
            this.queryRuleList(1);
            this.delDialog = false;
        });
    }
    handleSort(column): void {
        let sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        if (sortType) {
            this.sort = this.sortableObj[column.prop] + ' ' + sortType;
        } else {
            this.sort = '';
        }
        this.rulePage.currentPage = 1;
        this.queryRuleList(this.rulePage.currentPage);
    }
}
</script>
<style lang="scss" scoped>
.check-rule-table {
    padding: 15px;
    .search-box {
        padding: 15px;
        border: 1px solid #d7d7d7;
        margin-bottom: 15px;
    }
    .table-content {
        border: 1px solid #d7d7d7;
    }
    /deep/ .el-tag--success {
        background-color: #f6ffed;
        border-color: #b7eb8f;
        color: #52c41a;
    }
}
</style>
